import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author: gao
 * @create-date: 2025/3/2 12:41
 */

class TreeNode{
    int val;
    TreeNode left;
    TreeNode right;

    public TreeNode() {}

    public TreeNode(int val) {
        this.val = val;
    }

    public TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    public List<Integer> postorderTraversal(TreeNode root){
        List<Integer> tree = new ArrayList<>();

        if(root == null){
            return tree;
        }

        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode top = null;
        TreeNode prev = null;
        while(cur != null || !stack.isEmpty()) {
            while(cur != null){
                stack.push(cur);
                cur = cur.left;
            }
            top = stack.peek();
            if(top.right == null || top.right == prev){
                tree.add(top.val);
                stack.pop();
                prev = top;
            }else{
                cur = top.right;
            }
        }
        return tree;
    }
}